package com.shopx.cm.service.impl;


import com.shopx.auth.bean.SysOrg;
import com.shopx.auth.dao.db1.SysOrgDao;
import com.shopx.auth.model.SysOrgModel;
import com.shopx.auth.service.impl.BaseAuthService;
import com.shopx.cm.bean.CmMeasure;
import com.shopx.cm.bean.MaterialSaleDTO;
import com.shopx.cm.bean.MaterialSaleReqDTO;
import com.shopx.cm.dao.db2.MaterialSaleDao;
import com.shopx.cm.dto.MaterialSaleSyncDTO;
import com.shopx.cm.model.CmBrandCkModel;
import com.shopx.cm.service.ICmBrandCkService;
import com.shopx.cmm.DTO.PageDTO;
import com.shopx.base.constants.ResultCodeEnum;
import com.shopx.base.exception.ShopxException;
import com.shopx.base.exception.OriginException;
import com.shopx.base.service.ISysSeqService;
import com.shopx.base.service.base.BaseService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.shopx.core.utils.DateTimeUtil;
import com.shopx.core.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import com.shopx.dal.redis.CacheServiceFactory;
import com.shopx.cm.bean.CmSaleDetail;
import com.shopx.cm.model.CmSaleDetailModel;
import com.shopx.cm.dao.db1.CmSaleDetailDao;
import com.shopx.cm.service.ICmSaleDetailService;

/**
 * TODO
 *
 * @author lituo
 * @className: CmSaleDetail
 * @date 2025-03-05
 */
@Service
@Slf4j
public class CmSaleDetailServiceImpl extends BaseAuthService implements ICmSaleDetailService {

    @Resource
    private CmSaleDetailDao cmSaleDetailDao;

    @Resource
    private ISysSeqService sysSeqService;

    @Resource
    private MaterialSaleDao materialSaleDao;

    @Resource
    private ICmBrandCkService cmBrandCkService;

    @Resource
    private SysOrgDao sysOrgDao;

    @Value("${sync.saleDays}")
    private String saleDays;

    @Override
    public CmSaleDetailModel selectByPrimaryKey(CmSaleDetail cmSaleDetail) {
        if (cmSaleDetail == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        return cmSaleDetailDao.selectByPrimaryKey(cmSaleDetail);
    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public int insertSelective(CmSaleDetail cmSaleDetail) {
        if (cmSaleDetail == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        int result = cmSaleDetailDao.insertSelective(cmSaleDetail);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        return result;
    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public int updateByPrimaryKeySelective(CmSaleDetail cmSaleDetail) {
        if (cmSaleDetail == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        int result = cmSaleDetailDao.updateByPrimaryKeySelective(cmSaleDetail);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        return result;
    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public int deleteByPrimaryKey(CmSaleDetail cmSaleDetail) {
        if (cmSaleDetail == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        int result = cmSaleDetailDao.deleteByPrimaryKey(cmSaleDetail);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        return result;
    }

    @Override
    public int selectCount(CmSaleDetailModel cmSaleDetail) {
        return cmSaleDetailDao.selectCount(cmSaleDetail);
    }

    @Override
    public List<CmSaleDetailModel> selectList(CmSaleDetailModel cmSaleDetail) {
        List<CmSaleDetailModel> list = cmSaleDetailDao.selectList(cmSaleDetail);
        return list;
    }

    @Override
    public PageDTO<CmSaleDetailModel> getListPage(CmSaleDetailModel cmSaleDetail) {
        if (cmSaleDetail == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        PageDTO<CmSaleDetailModel> pageDTO = new PageDTO<CmSaleDetailModel>();
        pageDTO.setiTotalDisplayRecords(selectCount(cmSaleDetail));
        pageDTO.setData(selectList(cmSaleDetail));
        return pageDTO;
    }

    @Override
    public void syncSaleDt(){
        //清空数据
        cmSaleDetailDao.truncateTable();

        //查询T-1到T-365日的日期
        String curDt = DateTimeUtil.getDate8();
        log.info("syncSaleDt.begin:{}",curDt);

        MaterialSaleSyncDTO dto = new MaterialSaleSyncDTO();
        int disDays = Integer.parseInt(saleDays);
        for(int i=disDays;i>0;i--){
            String syncDt = DateTimeUtil.dateCalc(curDt,null,"D",i*(-1));
            dto.setBillDate(syncDt);
            List<MaterialSaleSyncDTO> list = materialSaleDao.querySaleDetail(dto);
            log.info("============开始同步{}日数据，总数据量：{}",syncDt,list.size());
            for (int j = 0; j < list.size(); j += 200) {
                try {
                    List<MaterialSaleSyncDTO> subList = list.subList(j, Math.min(j + 200, list.size()));
                    cmSaleDetailDao.insertBatch(subList);
                }catch (Exception e){
                    log.info("============{}日数据同步报错，报错原因：",syncDt,e);
                    log.error("syncSaleDt:{}.error:",syncDt,e);
                }
            }
            log.info("============{}日数据同步完成，总数据量：{}",syncDt,list.size());
        }
    }


    @Override
    public int querySalesByMaterialCnt(MaterialSaleReqDTO dto){
        return cmSaleDetailDao.querySalesByMaterialCnt(dto);
    }

    @Override
    public List<MaterialSaleDTO> querySalesByMaterialList(MaterialSaleReqDTO dto){
        //根据成控编码转换新品牌
        Map<String, CmBrandCkModel> map = cmBrandCkService.selectListByCode();
        List<MaterialSaleDTO> list = cmSaleDetailDao.querySalesByMaterialList(dto);
        for(MaterialSaleDTO record:list){
            record.setSupplyNewName(map.get(record.getCostSpecialCode().trim())==null?"无":map.get(record.getCostSpecialCode().trim()).getBrandName());
        }
        return list;
    }

    @Override
    public PageDTO<MaterialSaleDTO> getSalesByMaterial(MaterialSaleReqDTO dto){
        if (dto == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        if(StringUtil.isEmpty(dto.getBillBegDate()) || StringUtil.isEmpty(dto.getBillEndDate()) ){
            throw new OriginException("请输入时间段查询");
        }
        String billBegDate = dto.getBillBegDate().replaceAll("-","");
        String billEndDate = dto.getBillEndDate().replaceAll("-","");
        Long disDays = DateTimeUtil.getDistanceDay(billBegDate,billEndDate);
        if(disDays>370){
            throw new OriginException("最多间隔时间不能一年时间");
        }
        if(StringUtil.isEmpty(dto.getOrder())){
            dto.setOrder("t.materialClassName,t.orgCode,t.stock_num desc");
        }
        //转换组织机构
//        String userOrgId = super.getUserOrgId();
//        SysOrg sysOrg = new SysOrg();
//        sysOrg.setOrgId(userOrgId);
//        sysOrg.setCpId(super.getUserCpId());
//        SysOrgModel som = sysOrgDao.selectByPrimaryKey(sysOrg);
//        if(som==null){
//            throw new OriginException("获取部门信息失败");
//        }
        String  orgId = dto.getOrgCode();
        String orgIds[] = super.queryCondOrgIds(orgId);
        dto.setOrgIdChk(orgIds);
        //供货商转换成成控编码
        if(!StringUtil.isEmpty(dto.getSupplyNewName())){
            dto.setCostSpecialCode(this.getCodeByName(dto.getSupplyNewName()));
        }
        PageDTO<MaterialSaleDTO> pageDTO = new PageDTO<MaterialSaleDTO>();
        pageDTO.setiTotalDisplayRecords(querySalesByMaterialCnt(dto));
        pageDTO.setData(querySalesByMaterialList(dto));
        return pageDTO;
    }

    /**
     * 根据供货商名称，从缓存中获取成控编码
     * @param name
     * @return
     */
    private String getCodeByName(String name){
        Map<String, CmBrandCkModel> map = cmBrandCkService.selectListByMaterial();
        if(map.get(name)==null){
            return "";
        }
        return map.get(name).getCkCode();
    }

    @Override
    public List<MaterialSaleDTO> querySalesByGroupList(MaterialSaleReqDTO dto){
        //转换组织机构
//        String userOrgId = super.getUserOrgId();
//        SysOrg sysOrg = new SysOrg();
//        sysOrg.setOrgId(userOrgId);
//        sysOrg.setCpId(super.getUserCpId());
//        SysOrgModel som = sysOrgDao.selectByPrimaryKey(sysOrg);
//        if(som==null){
//            throw new OriginException("获取部门信息失败");
//        }
        List<MaterialSaleDTO> list = new ArrayList<>();
        String  orgId = dto.getOrgCode();
        String orgIds[] = super.queryCondOrgIds(orgId);
        dto.setOrgIdChk(orgIds);
        if("1".equals(dto.getGroupType())){
            //大区
            list =  cmSaleDetailDao.querySalesByRegionList(dto);
        }else if("2".equals(dto.getGroupType())){
            //品牌
            list = cmSaleDetailDao.querySalesBySpList(dto);
            Map<String, CmBrandCkModel>  map = cmBrandCkService.selectListByCode();
            for(MaterialSaleDTO record:list){
                //转换成品牌
                try {
                    record.setName(map.get(record.getName().trim()) == null ? "无" : map.get(record.getName().trim()).getBrandName());
                }catch (Exception e){
                    log.error("querySalesByGroupList.name:{}",record.getName());
                    record.setName("无");
                }
            }
        }else if("3".equals(dto.getGroupType())){
            //材料
            list =  cmSaleDetailDao.querySalesByNameList(dto);
        }

        BigDecimal allNumber = new BigDecimal(0);
        for(MaterialSaleDTO item:list){
            allNumber = allNumber.add(new BigDecimal(item.getValue()));
        }
        for(MaterialSaleDTO record:list){
            BigDecimal ratio = (new BigDecimal(record.getValue()).divide(allNumber, 2, RoundingMode.HALF_UP)).multiply(new BigDecimal(100));
            record.setName(record.getName().trim()+"["+record.getValue()+"/"+allNumber+"（占比："+ratio+"%）"+"]");
        }
        return list;
    }




    @Override
    public int querySalesByBrandCnt(MaterialSaleReqDTO dto){
        return cmSaleDetailDao.querySalesByBrandCnt(dto);
    }
    @Override
    public List<MaterialSaleDTO> querySalesByBrandList(MaterialSaleReqDTO dto){
        //根据成控编码转换新品牌
        Map<String, CmBrandCkModel>  map = cmBrandCkService.selectListByCode();
        List<MaterialSaleDTO> list = cmSaleDetailDao.querySalesByBrandList(dto);
        for(MaterialSaleDTO record:list){
            record.setSupplyNewName(map.get(record.getCostSpecialCode().trim())==null?"无":map.get(record.getCostSpecialCode().trim()).getBrandName());
        }
        return list;

    }
    @Override
    public PageDTO<MaterialSaleDTO> getSalesByBrand(MaterialSaleReqDTO dto){
        if (dto == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        if(StringUtil.isEmpty(dto.getBillBegDate()) || StringUtil.isEmpty(dto.getBillEndDate()) ){
            throw new OriginException("请输入时间段查询");
        }
        //转换组织机构
//        String userOrgId = super.getUserOrgId();
//        SysOrg sysOrg = new SysOrg();
//        sysOrg.setOrgId(userOrgId);
//        sysOrg.setCpId(super.getUserCpId());
//        SysOrgModel som = sysOrgDao.selectByPrimaryKey(sysOrg);
//        if(som==null){
//            throw new OriginException("获取部门信息失败");
//        }
        String  orgId = dto.getOrgCode();
        String orgIds[] = super.queryCondOrgIds(orgId);
        dto.setOrgIdChk(orgIds);
        //供货商转换成成控编码
        if(!StringUtil.isEmpty(dto.getSupplyNewName())){
            dto.setCostSpecialCode(this.getCodeByName(dto.getSupplyNewName()));
        }
        String billBegDate = dto.getBillBegDate().replaceAll("-","");
        String billEndDate = dto.getBillEndDate().replaceAll("-","");
        Long disDays = DateTimeUtil.getDistanceDay(billBegDate,billEndDate);
        if(disDays>370){
            throw new OriginException("最多间隔时间不能一年时间");
        }
        PageDTO<MaterialSaleDTO> pageDTO = new PageDTO<MaterialSaleDTO>();
        pageDTO.setiTotalDisplayRecords(querySalesByBrandCnt(dto));
        pageDTO.setData(querySalesByBrandList(dto));
        return pageDTO;
    }



    @Override
    public int querySalesByCodeCnt(MaterialSaleReqDTO dto){
        return cmSaleDetailDao.querySalesByCodeCnt(dto);
    }
    @Override
    public List<MaterialSaleDTO> querySalesByCodeList(MaterialSaleReqDTO dto){
        //根据成控编码转换新品牌
        Map<String, CmBrandCkModel>  map = cmBrandCkService.selectListByCode();
        List<MaterialSaleDTO> list = cmSaleDetailDao.querySalesByCodeList(dto);
        for(MaterialSaleDTO record:list){
            record.setSupplyNewName(map.get(record.getCostSpecialCode().trim())==null?"无":map.get(record.getCostSpecialCode().trim()).getBrandName());
        }
        return list;
    }
    @Override
    public PageDTO<MaterialSaleDTO> getSalesByCode(MaterialSaleReqDTO dto){
        if (dto == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        if(StringUtil.isEmpty(dto.getBillBegDate()) || StringUtil.isEmpty(dto.getBillEndDate()) ){
            throw new OriginException("请输入时间段查询");
        }
        //供货商转换成成控编码
        if(!StringUtil.isEmpty(dto.getSupplyNewName())){
            dto.setCostSpecialCode(this.getCodeByName(dto.getSupplyNewName()));
        }
        //转换组织机构
//        String userOrgId = super.getUserOrgId();
//        SysOrg sysOrg = new SysOrg();
//        sysOrg.setOrgId(userOrgId);
//        sysOrg.setCpId(super.getUserCpId());
//        SysOrgModel som = sysOrgDao.selectByPrimaryKey(sysOrg);
//        if(som==null){
//            throw new OriginException("获取部门信息失败");
//        }
        String  orgId = dto.getOrgCode();
        String orgIds[] = super.queryCondOrgIds(orgId);
        dto.setOrgIdChk(orgIds);
        String billBegDate = dto.getBillBegDate().replaceAll("-","");
        String billEndDate = dto.getBillEndDate().replaceAll("-","");
        Long disDays = DateTimeUtil.getDistanceDay(billBegDate,billEndDate);
        if(disDays>370){
            throw new OriginException("最多间隔时间不能一年时间");
        }
        PageDTO<MaterialSaleDTO> pageDTO = new PageDTO<MaterialSaleDTO>();
        pageDTO.setiTotalDisplayRecords(querySalesByCodeCnt(dto));
        pageDTO.setData(querySalesByCodeList(dto));
        return pageDTO;
    }



    @Override
    public int querySalesByMthCnt(MaterialSaleReqDTO dto){
        return cmSaleDetailDao.querySalesByMthCnt(dto);
    }
    @Override
    public List<MaterialSaleDTO> querySalesByMthList(MaterialSaleReqDTO dto){
        //根据成控编码转换新品牌
        Map<String, CmBrandCkModel>  map = cmBrandCkService.selectListByCode();
        List<MaterialSaleDTO> list = cmSaleDetailDao.querySalesByMthList(dto);
        for(MaterialSaleDTO record:list){
            record.setSupplyNewName(map.get(record.getCostSpecialCode().trim())==null?"无":map.get(record.getCostSpecialCode().trim()).getBrandName());
        }
        return list;

    }
    @Override
    public PageDTO<MaterialSaleDTO> getSalesByMth(MaterialSaleReqDTO dto){
        if (dto == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        if(StringUtil.isEmpty(dto.getBillBegDate()) || StringUtil.isEmpty(dto.getBillEndDate()) ){
            throw new OriginException("请输入时间段查询");
        }
        //转换组织机构
//        String userOrgId = super.getUserOrgId();
//        SysOrg sysOrg = new SysOrg();
//        sysOrg.setOrgId(userOrgId);
//        sysOrg.setCpId(super.getUserCpId());
//        SysOrgModel som = sysOrgDao.selectByPrimaryKey(sysOrg);
//        if(som==null){
//            throw new OriginException("获取部门信息失败");
//        }
        String  orgId = dto.getOrgCode();
        String orgIds[] = super.queryCondOrgIds(orgId);
        dto.setOrgIdChk(orgIds);
        //供货商转换成成控编码
        if(!StringUtil.isEmpty(dto.getSupplyNewName())){
            dto.setCostSpecialCode(this.getCodeByName(dto.getSupplyNewName()));
        }
        String billBegDate = dto.getBillBegDate().replaceAll("-","");
        String billEndDate = dto.getBillEndDate().replaceAll("-","");
        Long disDays = DateTimeUtil.getDistanceDay(billBegDate,billEndDate);
        if(disDays>370){
            throw new OriginException("最多间隔时间不能一年时间");
        }
        PageDTO<MaterialSaleDTO> pageDTO = new PageDTO<MaterialSaleDTO>();
        pageDTO.setiTotalDisplayRecords(querySalesByMthCnt(dto));
        pageDTO.setData(querySalesByMthList(dto));
        return pageDTO;
    }


    @Override
    public List<MaterialSaleDTO> querySalesListByCode(MaterialSaleReqDTO dto){
        if (dto == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        if(StringUtil.isEmpty(dto.getBillBegDate()) || StringUtil.isEmpty(dto.getBillEndDate()) ){
            throw new OriginException("请输入时间段查询");
        }
        if(StringUtil.isEmpty(dto.getSubCostSpecialCode())){
            throw new OriginException("请选择品类");
        }
        String billBegDate = dto.getBillBegDate().replaceAll("-","");
        String billEndDate = dto.getBillEndDate().replaceAll("-","");
        Long disDays = DateTimeUtil.getDistanceDay(billBegDate,billEndDate);
        if(disDays>370){
            throw new OriginException("最多间隔时间不能一年时间");
        }
        //转换组织机构
//        String userOrgId = super.getUserOrgId();
//        SysOrg sysOrg = new SysOrg();
//        sysOrg.setOrgId(userOrgId);
//        sysOrg.setCpId(super.getUserCpId());
//        SysOrgModel som = sysOrgDao.selectByPrimaryKey(sysOrg);
//        if(som==null){
//            throw new OriginException("获取部门信息失败");
//        }
        String  orgId = dto.getOrgCode();
        String orgIds[] = super.queryCondOrgIds(orgId);
        dto.setOrgIdChk(orgIds);

        Map<String, CmBrandCkModel>  map = cmBrandCkService.selectListByCode();
        List<MaterialSaleDTO> list = cmSaleDetailDao.querySalesListByCode(dto);
        //统计出所有的数据
        BigDecimal allNumber = new BigDecimal(0);
        for(MaterialSaleDTO item:list){
            allNumber = allNumber.add(new BigDecimal(item.getValue()));
        }
        for(MaterialSaleDTO record:list){
            BigDecimal ratio = (new BigDecimal(record.getValue()).divide(allNumber, 2, RoundingMode.HALF_UP)).multiply(new BigDecimal(100));
//            record.setName(record.getName().trim()+"["+record.getValue()+"/"+allNumber+"（占比："+ratio+"%）"+"]");
            record.setName(map.get(record.getName().trim())==null?"无":map.get(record.getName().trim()).getBrandName()+"["+record.getValue()+"/"+allNumber+"（占比："+ratio+"%）"+"]");
        }
        return list;
    }




    @Override
    public int querySalesByBrsCnt(MaterialSaleReqDTO dto){
        return cmSaleDetailDao.querySalesByBrsCnt(dto);
    }
    @Override
    public List<MaterialSaleDTO> querySalesByBrsList(MaterialSaleReqDTO dto){
        //根据成控编码转换新品牌
        List<MaterialSaleDTO> list = cmSaleDetailDao.querySalesByBrsList(dto);
        return list;
    }
    @Override
    public PageDTO<MaterialSaleDTO> getSalesByBrsList(MaterialSaleReqDTO dto){
        if (dto == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        if(StringUtil.isEmpty(dto.getBillBegDate()) || StringUtil.isEmpty(dto.getBillEndDate()) ){
            throw new OriginException("请输入时间段查询");
        }
        //转换组织机构
        String  orgId = dto.getOrgCode();
        String orgIds[] = super.queryCondOrgIds(orgId);
        dto.setOrgIdChk(orgIds);
        String billBegDate = dto.getBillBegDate().replaceAll("-","");
        String billEndDate = dto.getBillEndDate().replaceAll("-","");
        Long disDays = DateTimeUtil.getDistanceDay(billBegDate,billEndDate);
        if(disDays>370){
            throw new OriginException("最多间隔时间不能一年时间");
        }
        PageDTO<MaterialSaleDTO> pageDTO = new PageDTO<MaterialSaleDTO>();
        pageDTO.setiTotalDisplayRecords(querySalesByBrsCnt(dto));
        pageDTO.setData(querySalesByBrsList(dto));
        return pageDTO;
    }
}

